package com.shebei.api.equipment_api_test.http;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class HttpClientJson implements HttpClienInterface {



    @Override
    public String sendRequest(String url, String requestBody, Map<String, String> head) {




        String res=doPostJson( url,  requestBody,head);

        return res;
    }



    private   String doPostJson(String url, String json,Map<String, String> head) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求

                HttpPost httpPost = new HttpPost(url);

            if (head != null){
                for (String key : head.keySet()) {
                    httpPost.setHeader(key,String.valueOf(head.get(key)));
                }


            }


            // 创建请求内容
            if(json!=null&&!json.equals("")){
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }

            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
//           String cookie=getHeadCookie(response,url);
//           if(cookie!=null && resultString!=null){
//               JSONObject jsonObject1 =JSONObject.parseObject(resultString);
//               jsonObject1.put("cookie",cookie);
//               resultString=jsonObject1.toJSONString();
//           }

            resultString= getCookie(response,url,resultString);
            System.out.println("请求response为："+resultString);


        } catch (Exception e) {
            // log.error(e.getMessage(),e);
        } finally {
            try {
                if (null !=response){
                    response.close();
                }
            } catch (IOException e) {
                // log.error(e.getMessage(),e);
            }
        }

        return resultString;
    }

//获取cookie
    private String getHeadCookie(CloseableHttpResponse response,String url){
        if(!url.contains("login")){
              return null;
        }
        Header[] headers= response.getAllHeaders();
        String USERSESSIONID=null;
        String user_token=null;
        for(int i=0;i<headers.length;i++){
            Header header=headers[i];
            String value=header.getValue();
            String name=header.getName();
            if(value.startsWith("USERSESSIONID")){
                System.out.println("USERSESSIONID:"+value);
                String[] values=value.split(";");
                USERSESSIONID=values[0];
            }
            if(value.startsWith("user_token")){
                System.out.println("user_token:"+value);
                String[] values=value.split(";");
                user_token=values[0];
            }
            System.out.println("HeaderName:"+name +";"+"HeaderValue:"+value);
        }
        String cookie=USERSESSIONID+"; "+user_token ;

        return cookie;
    }


    private  String getCookie(CloseableHttpResponse response,String url,String resultString){
        if(!url.contains("/login")){ //不是登录 直接返回
            return resultString;
        }

      Boolean isJson=false;

        Header[] headers= response.getAllHeaders();
        List<JSONObject> setCookie=new ArrayList<>();
        for(int i=0;i<headers.length;i++){
            Header header=headers[i];
            String value=header.getValue();
            String name=header.getName();
            if(name.equals("Set-Cookie")){
                JSONObject tmp=new JSONObject();
                tmp.put("SetCookie",value);
                setCookie.add(tmp);
            }
            if(name.equals("Content-Type") && value.contains("application/json")){
                isJson=true;


            }

        }

        if(isJson){
            JSONObject jsonObject1 =JSONObject.parseObject(resultString);
            jsonObject1.put("Cookie",setCookie);
            return jsonObject1.toJSONString();
        }

        JSONObject jsonObject= new JSONObject();
        jsonObject.put("Set-Cookie",setCookie);
        jsonObject.put("Response",resultString);

        return jsonObject.toJSONString();
    }


}
